const userTable = require('../models/userTable')
const inspirecloud = require('@byteinspire/api')
const ObjectId = inspirecloud.db.ObjectId
const { randomString, md5 } = require('../utils')
const enums = require('../enums')

class UserService {
  // 注册服务，根据返回值判断是否注册成功
  async regiser(userInfo) {
    // 判断用户名是否存在
    if (
      await userTable.where({ username: userInfo.username }).limit(1).count()
    ) {
      return enums.USER_EXIST
    }
    // 生成数据写入数据库
    const salt = randomString(8)
    const password = md5(`${md5(userInfo.password)}${md5(salt)}`)
    await userTable.save({
      username: userInfo.username,
      password,
      salt,
    })
    return enums.SUCCESS
  }

  async login(userInfo) {
    const user = await userTable
      .where({ username: userInfo.username })
      .findOne()
    // 是否存在用户
    if (!user) {
      return {
        code: enums.USER_NOT_FOUND,
      }
    }
    // 判断密码是否正确
    if (user.password != md5(`${md5(userInfo.password)}${md5(user.salt)}`)) {
      return {
        code: enums.USER_INFO_ERROR,
      }
    }
    return {
      code: enums.SUCCESS,
      data: {
        ...user,
      },
    }
  }
  async setAvatar(uid, url) {
    const user = await userTable.where({ _id: ObjectId(uid) }).findOne()
    user.avatar = url
    userTable.save(user)
  }
}

module.exports = new UserService()
